<template>
    <transition name="el-fade-in">
        <FloatPanel v-if="showFloatPanel" @closeOperatePanel="closePanel" @operateAll="handleOperateAll" :selectedList="selectedArr" />
    </transition>
    <el-dialog
    v-model="isShowImportBox"
    title="批量导入数据"
    width="99%"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    @closed="clearAllFiles"
    center
    destroy-on-close
  >
    <div class="import-container">
        <div class="left-file-zone">
            <span class="guide">第一步:(1)单击<strong>选择文件</strong>按钮选择xlsx或csv文件(2)单击<strong>导入文件</strong>按钮。</span>
            <el-upload
                ref="fileRef"
                class="import-file"
                action="#"
                :on-change="getImportFile"
                :on-remove = "removeImportFile('table')"
                :limit="1"
                :on-exceed="exceedTip"
                accept=".csv,.xlsx,.xls"
                :auto-upload="false"
            >
                <template #trigger>
                    <el-button type="primary" :disabled="showChooseFile">选择文件</el-button>
                </template>
                <el-tooltip
                        effect="dark"
                        content="导入数据"
                        placement="top"
                        v-if="!showChooseFile"
                    >	
                <Icon icon="publish-dark" size="30px"  @click="submitImportFile('table')" />
                </el-tooltip>
                <el-progress v-if="isShowProgressBar" type="circle" :width="50" :percentage="contentStore.progress" />
            </el-upload>
            <div class="list-container" width="100%" >
                <el-table :data="importedList" stripe :border="true" width="100%">
                    <el-table-column prop="title" label="电影名">
                        <template #default="scope">
                            <el-tooltip :content="scope.row.title" placement="top">
                                <span>{{ scope.row.title }}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column prop="img" label="图片名"   />
                </el-table>
            </div>
        </div>
        <div class="right-file-zone">
            <span class="guide">第二步:(1)单击<strong>选择图片</strong>按钮,选取与左侧列表相似电影名的图片文件(2)单击<strong>匹配海报</strong>按钮进行匹配(3)单击<strong>导入图片</strong>按钮。</span>
            <el-upload
                v-if="showChoosePoster"
                ref="imgRef"
                class="import-file"
                action="#"
                multiple
                :on-change="getImportFile"
                accept=".webp"
                :show-file-list="false"
                :auto-upload="false"
            >
                <template #trigger>
                    <el-button type="primary">选择图片</el-button>
                </template>
                <el-tooltip
                        v-if="showUploadButton"
                        effect="dark"
                        content="导入图片"
                        placement="top"
                    >	
                <Icon icon="publish-dark" size="30px" @click="submitImportFile('img')" />
                </el-tooltip>
                <transition name="el-zoom-in-center">
                    <el-button v-if="showMatchButton" type="success" round @click="matchPoster">匹配海报</el-button>
                </transition>
                
            </el-upload>
            <div class="result-info-container" v-if="showResult">
                    <span>成功:&nbsp;&nbsp;{{ successCount }}&nbsp;&nbsp;</span>
                    <span>错误:&nbsp;&nbsp;{{ errorCount }}&nbsp;&nbsp;</span>
                    <el-popover placement="right" :width="400" trigger="click">
                        <template #reference>
                            <Icon icon="info-tip" size="30px" />
                        </template>
                        <el-table :data="posterResult" >
                            <el-table-column width="100" property="name" label="name" />
                        </el-table>
                    </el-popover>
                </div>
            <div class="img-container">
                <el-table :data="posterList" stripe :border="true" width="100%">
                    <el-table-column prop="name" label="图片名" />
                    <el-table-column prop="opreate" label="操作" >
                        <template #default="scope">
                            
                            <el-popover placement="top" :width="300" trigger="click">
                                <template #reference>
                                    <el-button  type="info" round @click="viewPoster(scope.row.id)">{{scope.row.operate[0]}}</el-button>
                                </template>
                                <div class="preview-img">
                                    <img :src="scope.row.preview" alt="海报">
                                </div>
                            </el-popover>
                            <el-button  type="danger" round @click="deletePoster(scope.row.id)">{{scope.row.operate[1]}}</el-button>
                        </template>  
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
  </el-dialog>
    <el-dialog
    v-model="isShowDetailBox"
    title="影视信息"
    width="800"
    :close-on-press-escape="false"
    :center="true"
  >
    <div class="mtv-info-wrapper">
        <el-form
            ref="mtvTableRef"
            :model="boundData"
            :rules="rulesMTV"
            label-width="120px"
            :disabled="operateType"
            status-icon
        >
        <el-form-item label="名称" prop="title">
                <el-input v-model="boundTitle" />
            </el-form-item>
            <el-form-item label="导演" prop="director">
                <Tags tagType="director" />
            </el-form-item>
            <el-form-item label="编剧" prop="scriptWriter">
                <Tags tagType="scriptWriter" />
            </el-form-item>
            <el-form-item label="演员" prop="actors">
                <Tags tagType="actors"  />
            </el-form-item>
            <el-form-item label="类型" prop="contentClass">
                <Tags tagType="contentClass" />
            </el-form-item>
            <el-form-item label="地区" prop="area">
                <el-select
                    v-model="boundArea"
                    multiple
                    filterable
                    placeholder="请选择地区"
                    style="width: 240px"
                    >
                    <el-option
                        v-for="item in areaOptions"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="语言" prop="lang">
                <Tags tagType="lang" />
            </el-form-item>
            <el-form-item label="上映日期" prop="date">
                <el-input v-model="boundDate" />
            </el-form-item>
            <el-form-item label="时长" prop="duration">
                <el-input v-model="boundDuration" />
            </el-form-item>
            <el-form-item label="评分" prop="totalGrade">
                <el-input v-model="boundTotalGrade" />
            </el-form-item>
            <el-form-item label="剧情" prop="synopsis">
                <el-input type="textarea" autosize resize="none" show-word-limit minlength="10" maxlength="500" v-model="boundSynopsis" />
            </el-form-item>
            <el-form-item label="海报" prop="posterImg">
                <el-upload ref="uploadRef" action="#" :limit="1" :on-exceed="handleExceed" list-type="picture" :on-change="file=>handleImgChange(file,fileList,'add')" :on-remove="file=>handleImgChange(file,fileList,'delete')" :auto-upload="false">
                      <img @mouseover="openPreviewBox(true)" style="object-fit:contain;width:67.5px;height:100px" :src="displayMode === 'add'?currentAdd.posterImg:currentEdit.item.posterImg" alt="海报" />
                      <Icon icon="upload-image" size="50px" />
                </el-upload>
                <el-dialog v-model="previewBox" draggable title="预览海报" width="500" center>
                    <img @mouseover="openPreviewBox(true)" :src="displayMode === 'add'?currentAdd.posterImg:currentEdit.item.posterImg" class="poster-preview" alt="大海报"/>
                </el-dialog>
            </el-form-item>
            <el-form-item label="分类" prop="artType">
                <el-radio-group v-model="boundArtType">
                    <el-radio label="电影">电影</el-radio>
                    <el-radio label="电视剧">电视剧</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="上传时间" prop="uploadTime">
                <el-date-picker
                    v-model="boundUploadTime"
                    type="datetime"
                    placeholder="请选择日期和时间"
                />
            </el-form-item>
            <el-form-item label="收藏量" prop="markNum">
                <el-input-number v-model="boundMarkNum" :min="0"  />
            </el-form-item>
            <el-form-item label="短评" prop="quote">
                <el-input v-model="boundQuote" minlength="2" maxlength="10" />
            </el-form-item>
            <el-form-item v-if="!operateType">
                <el-button v-if="displayMode === 'edit'" type="primary" @click="editMTV()">
                    提交
                </el-button>
                <el-button v-else type="primary" @click="addMTV()">
                    提交
                </el-button>
            </el-form-item>
        </el-form>
    </div>
  </el-dialog>
    <div class="mtv-info-container">
        <!-- 顶部筛选 -->
        <div class="top-query">
            <el-page-header :icon="ArrowLeft" v-show="showHeader" @click="backToNormal">
                <template #content>
                    <span @click.stop="stopClickPropagation">检索结果</span>
                </template>
            </el-page-header>
            <el-form :inline="true" ref="queryRef" :rules="queryRule" :model="formline" class="query-form">
                <el-form-item label="检索" prop="keywords">
                    <el-input v-model="formline.keywords" @keyup.enter="queryFilterMTV" placeholder="请输入影视名关键字" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="queryFilterMTV" :icon="Search">查询</el-button>
                </el-form-item>
            </el-form>
          <div class="class-filter">
            <label>分类</label>
                <el-radio-group v-model="mtv_class">
                    <el-radio label="全部">全部</el-radio>
                    <el-radio label="电影">电影</el-radio>
                    <el-radio label="电视剧">电视剧</el-radio>
                </el-radio-group>
          </div>
          <div class="add-mtvInfo">
            <el-button type="warning" @click="openDetailBox(true,null,'add')" :icon="Plus" circle />
          </div>
          <Icon @click="openImportBox()" class="data-import" icon="import" size="40px" />
        </div>
        <el-divider />
        <!-- MTV影视信息表格 -->
        <div class="mtv-table-wrapper"> 
            <el-table
                class="user-table"
                :data="mtvTable"
                ref="multipleTableRef"
                :reserve-selection="true"
                @selection-change="handleSelectionChange"
                :border="true">
                <el-table-column type="selection" width="55" :align="'center'" />
                <el-table-column prop="id" label="ID" min-width="100" :align="'center'" />
                <el-table-column prop="title" label="名称" min-width="200"  :align="'center'" />
                <el-table-column prop="posterImg" label="海报" min-width="100" :align="'center'">
                    <template #default="scope"> 
                        <div class="poster-wrapper">
                            <el-image
                            style="width: 67.5px; height: 100px;"
                            preview-teleported
                            :src="scope.row.posterImg"
                            lazy
                            :zoom-rate="1.2"
                            :max-scale="7"
                            :min-scale="0.2"
                            :preview-src-list="[scope.row.posterImg]"
                            :initial-index="0"
                            fit="cover"
                            > 
                            <template #placeholder>
                                <div class="image-slot">
                                    <Icon icon="error-img-loading" size="50px" />
                                </div>
                            </template>
                        </el-image>
                        </div> 
                    </template>  
                </el-table-column>
                <el-table-column prop="totalGrade" label="评分" sortable  width="80" :align="'center'" />
                <el-table-column prop="contentClass" label="类型" min-width="120" :align="'center'" /> 
                <el-table-column prop="artType" label="分类" width="80" :align="'center'" />
                <el-table-column prop="markNum" label="收藏量" min-width="120" :align="'center'" />    
                <el-table-column prop="uploadTime" label="上传时间" sortable width="160" :align="'center'" />
                <el-table-column prop="opreate" label="操作" min-width="250" max-width="310" :align="'center'" >
                    <template #default="scope">
                        <el-button  size="small"  type="info" :icon="View"   round @click="openDetailBox(true,scope.row.id,'view')">查看</el-button>
                        <el-button  size="small" type="primary" :icon="Edit" round @click="openDetailBox(true,scope.row.id,'edit')">编辑</el-button>
                        <el-button size="small"  type="danger" :icon="Delete" round @click="deleteMTV(scope.row.id)">删除</el-button>
                    </template>  
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页部分 -->
        <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :page-count="parseInt(total%pageSize === 0?total/pageSize:total/pageSize+1)"
                :background="true"
                layout="total, prev, pager, next, jumper"
                :total="total"
                >
            </el-pagination>
        </div>
    </div>
</template>
  
<script setup>
    import { ref,computed,reactive,onBeforeMount,watch} from 'vue';
    import Icon from '@/components/Icon.vue';
    import Tags from '@/components/content/tags.vue';
    import FloatPanel from '@/components/floatPanel.vue';
    import {fileToDataURL,unique,matchAndReplace,renameFile} from '@/utils/common.js';
    import {useContentStore} from '@/store/modules/content.js';
    import {importMtvInfo,importMtvPosters, editMtvInfo,addMtvInfo,getMtvInfo,deleteMtvInfo,deleteMtvInfoBatch,getFilterMTV,getDiffClassMtv} from '@/api/index.js';
    import {Delete,Edit,Search,View,Plus,ArrowLeft} from '@element-plus/icons-vue'
    import {genFileId,ElInputNumber,ElProgress,ElPageHeader,ElDivider,ElNotification,ElTooltip,ElUpload,ElDatePicker,ElMessage,ElLoading, ElMessageBox,ElForm, ElFormItem, ElButton,ElInput,ElSelect,ElRadioGroup,ElPagination,ElTableColumn,ElPopover,ElTable,ElDialog,ElRadio,ElOption,ElImage } from 'element-plus'
    const mtvTable = ref(null);
    /*pinia数据*/
    const  contentStore = useContentStore();
    const operateType = ref(true);//默认是查看模式
    /*当前用户数据*/
    const currentEdit  = reactive({
        id:null,
        item:{}
    });
    let displayMode = ref('view');
    let currentAdd = reactive({
            actors:[],
            area:[],
            artType:"",
            contentClass:[],
            date:"",
            director:[],
            duration:"",
            id:null,
            lang:[],
            markNum:0,
            posterImg:"",
            quote:"",
            scriptWriter:[],
            synopsis:"",
            title:"",
            totalGrade:"0",
            uploadTime:"",
        });
    /*绑定的计算属性*/
    const boundData = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item : currentAdd;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item = value;  
            } else {  
            currentAdd = value;  
            }  
        }
    })
    
    const boundMode = computed({
        get() {  
            return displayMode.value === 'add';  
        },  
        set(value) {  
            displayMode.value = value;  
        }
    })
    const boundTitle = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.title : currentAdd.title;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.title = value;  
            } else {  
            currentAdd.title = value;  
            }  
        }
    });
    const boundArea = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.area : currentAdd.area;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.area = value;  
            } else {  
            currentAdd.area = value;  
            }  
        }
    });
    const boundDate = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.date : currentAdd.date;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.date = value;  
            } else {  
            currentAdd.date = value;  
            }  
        }
    });
    const boundDuration = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.duration : currentAdd.duration;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.duration = value;  
            } else {  
            currentAdd.duration = value;  
            }  
        }
    });
    const boundTotalGrade = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.totalGrade : currentAdd.totalGrade;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.totalGrade = value;  
            } else {  
            currentAdd.totalGrade = value;  
            }  
        }
    });
    const boundSynopsis = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.synopsis : currentAdd.synopsis;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.synopsis = value;  
            } else {  
            currentAdd.synopsis = value;  
            }  
        }
    });
    const boundArtType = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.artType : currentAdd.artType;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.artType = value;  
            } else {  
            currentAdd.artType = value;  
            }  
        }
    });
    const boundUploadTime = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.uploadTime : currentAdd.uploadTime;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.uploadTime = value;  
            } else {  
            currentAdd.uploadTime = value;  
            }  
        }
    });
    const boundMarkNum = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.markNum : currentAdd.markNum;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.markNum = value;  
            } else {  
            currentAdd.markNum = value || 0;  
            }  
        }
    });
    const boundQuote = computed({
        get() {  
            return displayMode.value !== 'add' ? currentEdit.item.quote : currentAdd.quote;  
        },  
        set(value) {  
            if (displayMode.value !== 'add') {  
            currentEdit.item.quote = value;  
            } else {  
            currentAdd.quote = value || '探索影像的魅力，体验电影的魔力。';  
            }  
        }
    });
    let fileUrl = ref(null);
/*表单的模板引用以及数据*/
const queryRef = ref(null);
const mtvTableRef = ref(null);
const uploadRef = ref(null);
const multipleTableRef = ref(null);
let fileRef = ref(null);
let imgRef = ref(null);
/*地区数组*/
const areaOptions =  [  
    "美国", "加拿大", "墨西哥", "巴西", "阿根廷", "哥伦比亚",  
    "英国", "法国", "德国", "意大利", "西班牙", "俄罗斯",  
    "中国", "中国香港", "中国台湾", "日本", "韩国", "印度",  
    "澳大利亚", "新西兰", "南非", "埃及", "摩洛哥", "埃塞俄比亚",  
    "沙特阿拉伯", "阿联酋", "以色列", "伊朗", "巴基斯坦",  
    "越南", "泰国", "马来西亚", "新加坡", "印度尼西亚",  
    "肯尼亚", "坦桑尼亚", "乌干达", "加纳", "摩洛哥",  
    "阿尔及利亚", "利比亚", "突尼斯", "摩洛哥", "南非",  
    "阿根廷", "智利", "秘鲁", "玻利维亚", "厄瓜多尔",  
    "尼日利亚", "加纳", "肯尼亚", "安哥拉", "刚果",  
    "波兰", "捷克", "匈牙利", "斯洛伐克", "罗马尼亚",  
    "保加利亚", "塞尔维亚", "克罗地亚", "斯洛文尼亚",  
    "丹麦", "瑞典", "挪威", "冰岛", "芬兰",  
    "希腊", "土耳其", "塞浦路斯",  
    "匈牙利", "奥地利", "瑞士", "比利时", "荷兰",  
    "爱尔兰", "苏格兰", "威尔士",  
    "以色列", "约旦", "黎巴嫩", "叙利亚", "伊拉克",  
    "乌兹别克斯坦", "哈萨克斯坦", "吉尔吉斯斯坦", "塔吉克斯坦", "土库曼斯坦",  
    "蒙古", "朝鲜", "阿富汗", "尼泊尔", "孟加拉",  
    "斯里兰卡", "马尔代夫", "不丹",  
    "缅甸", "老挝", "柬埔寨", "越南", "泰国",  
    "菲律宾", "马来西亚", "新加坡", "印度尼西亚", "文莱",  
    "东帝汶", "新西兰", "斐济", "萨摩亚", "库克群岛",  
    "智利", "秘鲁", "玻利维亚", "厄瓜多尔", "哥伦比亚",  
    "委内瑞拉", "圭亚那", "苏里南", "法属圭亚那", "乌拉圭",  
    "阿根廷", "巴西", "巴拉圭", "秘鲁", "智利",  
    "阿根廷", "乌拉圭", "巴拉圭", "苏里南", "法属圭亚那",  
    "圭亚那", "委内瑞拉", "哥伦比亚", "巴西", "玻利维亚",  
    "秘鲁", "厄瓜多尔", "智利", "阿根廷", "乌拉圭",  
    "巴拉圭", "巴西", "玻利维亚", "哥伦比亚", "委内瑞拉",  
    "苏里南", "圭亚那", "法属圭亚那",  
    "阿尔巴尼亚", "安道尔", "奥地利", "白俄罗斯", "保加利亚",  
    "克罗地亚", "捷克", "爱沙尼亚", "梵蒂冈", "芬兰",  
    "德国", "直布罗陀", "希腊", "匈牙利", "冰岛",  
    "爱尔兰", "意大利", "拉脱维亚", "列支敦士登", "立陶宛",  
    "卢森堡", "马其顿", "马尔他", "摩尔多瓦", "摩纳哥",  
    "黑山", "荷兰", "挪威", "波兰", "葡萄牙",  
    "罗马尼亚", "俄罗斯", "圣马力诺", "塞尔维亚", "斯洛伐克",  
    "斯洛文尼亚", "西班牙", "瑞典", "瑞士", "乌克兰",  
    "英国", "梵蒂冈"  
];  
const rulesMTV = {
    title:[
        { required: true, message: '请输入电影名称', trigger: 'blur' },
    ],
    director:[
        { required: true, message: '请输入电影名称', trigger: 'blur' },
        ],
    scriptWriter:[
        { required: true, message: '请输入编剧名称', trigger: 'blur' },
    ],
    actors:[
        { required: true, message: '请输入演员名称', trigger: 'blur' },
    ],
    contentClass:[
        { required: true, message: '请输入电影类型', trigger: 'blur' },
    ],
    area:[
        { required: true, message: '请输入电影地区', trigger: 'blur' },
    ], 
    lang:[
        { required: true, message: '请输入电影语种', trigger: 'blur' },
    ],
    date:[
        { required: true, message: '请输入电影上映日期', trigger: 'blur' },
    ],
    duration:[
        { required: true, message: '请输入影视时长', trigger: 'blur' },
    ],
    totalGrade:[
        { required: true, message: '请输入电影总评分', trigger: 'blur' },
    ],
    synopsis:[
        { required: true, message: '请输入电影简介', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符之间', trigger: 'blur'}
    ],
    posterImg:[
        { required: true, message: '请上传电影海报', trigger: 'blur' },
    ],
    artType:[
        { required: true, message: '请选择艺术类型', trigger: 'blur' },
    ],
    uploadTime:[
        { required: true, message: '请选择上传时间', trigger: 'blur' },
    ],
};
const formline = reactive({keywords:''});
let fileObj = ref(null);
let importFile = ref(null);
const checkKeywords = (rule, value, callback) => {
    const regex = /[\s~`!@#$%^&*()\\-_=+[\]{}|;:'",<.>/?]/;
      const result = regex.test(value);
      if (result) {
        callback(new Error("关键字中请勿包含特殊字符"));
      } else {
        callback();
      }
}
const queryRule = {
    keywords:[
        { required: true, message: '请输入关键字', trigger: 'blur' },
        { type:'string',validator:checkKeywords,trigger: 'change'}
    ] 
};
//默认分类全部
const mtv_class  = ref('全部');

let isShowProgressBar = ref(false);
/*分页*/
let currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const order = ref('asc');
const orderBy = ref('id');
onBeforeMount(()=>{
            //orderBy order limit offset
        getMtvList(orderBy.value,order.value,pageSize.value,0);
});
watch(currentPage,(newVal)=>{
    let offset = (newVal-1)*pageSize.value;
    getMtvList(orderBy.value,order.value,pageSize.value,offset);  
});
watch(mtv_class,()=>{
    queryDiffClassMtv();
});
/*详情或编辑操作弹窗*/
const isShowDetailBox = ref(false);
const isShowImportBox = ref(false);
const showMatchButton = ref(false);
const showResult = ref(false);
const showUploadButton = ref(false);//第二步上传按钮默认隐藏
const showChoosePoster = ref(false);
const showChooseFile = ref(false);
const showHeader = ref(false);
/*已导入列表*/
const importedList = ref([]);
const posterList = ref([]);
const successCount = ref(0);
const errorCount = ref(0);
const posterResult= ref([]);
const showFloatPanel = ref(false);
const selectedArr = ref([]);
//是否打开详情窗口
const openDetailBox = (val,index,type)=>{
const loading = ElLoading.service({
    lock: true,
    text: '稍等,加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  });
    isShowDetailBox.value = val;
    operateType.value = type === 'view';
    contentStore.operate_mode = type;
    displayMode.value = type;
    if(type !== 'add'){
        currentEdit.id = index;
        //创建副本防止table中的数据被直接引用导致其被污染
        let tmp = mtvTable.value.find(item => item.id === index);
        let tmp2 = JSON.parse(JSON.stringify(tmp));
        currentEdit.item = tmp2;
        contentStore.mtvInfo = tmp2;
    }else{
        contentStore.mtvInfo = currentAdd;
    }
    loading.close();
}
//获取影视列表
const getMtvList = (orderBy,order,limit,offset)=>{
    //orderBy order limit offset
    getMtvInfo({orderBy,order,limit,offset}).then(res => {
        if(res.status.code === 200){
            let tmp = res.data.list;
            mtvTable.value = washDataArr(tmp);
            total.value = res.data.total;
        }else{
            ElMessage.error(res.status.msg);
        }
    });  
}
//刷新视图
const refreshView = ()=>{
    let offset = (currentPage.value-1)*pageSize.value;
    getMtvList(orderBy.value,order.value,pageSize.value,offset);
}
//清洗后端发过来的数据
const washDataArr = (arr)=>{
    arr.forEach(item => {
        item.contentClass = handleTagArr(item.contentClass,'/');
        item.scriptWriter = handleTagArr(item.scriptWriter,'/');
        item.director = handleTagArr(item.director,'/');
        item.area = handleTagArr(item.area,'/');
        item.lang = handleTagArr(item.lang,'/');
        item.actors = handleTagArr(item.actors,'#');
    });
    return arr;
}
const closePanel = ()=>{
    multipleTableRef.value.clearSelection();
    showFloatPanel.value = false;
}
//根据分类筛选电影
const queryDiffClassMtv = ()=>{
    getDiffClassMtv({Class:mtv_class.value,orderBy:orderBy.value,order:order.value,limit:pageSize.value,offset:0}).then(res => {
        if(res.status.code === 200){
            mtvTable.value = washDataArr(res.data.list);
            total.value = res.data.total;
            showHeader.value = true;
        }else{
            ElMessage.error(res.status.msg);
        }
    });
}
//处理批量操作
const handleOperateAll = (val)=>{
    if(val === 'delete'){
        let idArr = selectedArr.value.map(item => item.id);
        if(idArr.length === 0) {
            ElMessage.error('请选择要删除的数据');
            return;
        }
        ElMessageBox.confirm(
            '确定永久性删除已选中列表中的数据吗?',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal:false,
                closeOnPressEscape:false,	
                draggable:true,
                showClose:false,
                type: 'warning',
                center: true,
            }).then(() => {
                //向后端发起删除请求
                IdentifyUser(idArr,'batch');
            }).catch(() => {});
    }else{
        if(val !== 'all'){
            selectedArr.value = selectedArr.value.filter(item => item.id !== val);
        }else{
            selectedArr.value = [];
            multipleTableRef.value.clearSelection();
        }
    }
}
//打开窗口
const openImportBox= ()=>{
    isShowImportBox.value = true;
}
//处理tag数组
const handleTagArr = (obj,sign)=>{
    let arr = [];
    if(obj){
         arr = obj.split(sign);
        for(let i=0;i<arr.length;i++){
        if(arr[i]==='' || arr[i].includes('|导演')){
            arr.splice(i,1);
            i--;
        }
        }
    }
    return arr;
}
//处理选中改变
const handleSelectionChange = (val)=>{
    let tmp = val.map(({id,title}) => ({id,title}));
    tmp.forEach(item => {
        selectedArr.value.push(item);
    });
    selectedArr.value=unique(selectedArr.value,'id');
    //打开浮窗
    showFloatPanel.value = true;
}
//处理图片的改变
const handleImgChange = (file,fileList,type)=>{
    if(type === 'add'){
        fileUrl.value = file.url;
        fileObj = file.raw;
    }else{
        uploadRef.value.clearFiles();
        fileUrl.value = '';
        fileObj = null;
    }
    if(displayMode.value === 'add'){
        currentAdd.posterImg = file.url;
    }else{
        currentEdit.item.posterImg = file.url;
    }
}
//替换之前上传的图片
const handleExceed = (files) => {
      uploadRef.value.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      uploadRef.value.handleStart(file);
}
const backToNormal = () => {
    showHeader.value = false;
    refreshView();
}
const stopClickPropagation=(e)=> {
      e.stopPropagation(); // 阻止事件冒泡
}
/*筛选查询影视数据*/
const queryFilterMTV = () => {
    queryRef.value.validate((valid) => {
        if(!valid) return;
        //向后端发送请求
        let keywords = formline.keywords.trim();
        getFilterMTV({orderBy:orderBy.value,order:order.value,limit:pageSize.value,offset:0,keywords}).then(res => {
            if(res.status.code === 200){
                let tmp = res.data.list;
                mtvTable.value = washDataArr(tmp);
                total.value = res.data.total;
                showHeader.value = true;
            }else{
                ElMessage.error(res.status.msg);
            }
        })
    })
}
//添加影视数据
const addMTV = () => {
    mtvTableRef.value.validate((valid) => {
        if(!valid) return;
        //向后端发送请求
        let handler = {
        get: function(target, prop) {
            return target[prop];
            }
        };
        let proxy = new Proxy(boundData, handler);
        let formData = new FormData();
        formData.append('file',fileObj);
        for (let key in proxy.value) { 
            if(Array.isArray(proxy.value[key])){
                formData.append(key,proxy.value[key].join('/'));
            }else{
               formData.append(key,proxy.value[key]);
            }
        }
        addMtvInfo(formData).then((res)=>{
            if(res.status.code === 200){
                ElMessage.success(res.status.msg);
                isShowDetailBox.value = false;
            }else{
                ElMessage.error(res.status.msg);
            }
            refreshView();
        });
    })
}
//编辑影视数据
const editMTV = () => {
    mtvTableRef.value.validate((valid) => {
        if(!valid) return;
        //向后端发送请求
        let handler = {
        get: function(target, prop) {
            return target[prop];
            }
        };
        let proxy = new Proxy(boundData, handler);
        let formData = new FormData();
        formData.append('file',fileObj);
        for (let key in proxy.value) {
            if(Array.isArray(proxy.value[key])){
                formData.append(key,proxy.value[key].join('/'));
            }else{
                formData.append(key,proxy.value[key]);
            }
        }
        editMtvInfo(formData).then((res)=>{
            if(res.status.code === 200){
                ElMessage.success(res.status.msg);
                isShowDetailBox.value = false;
            }else{
                ElMessage.error(res.status.msg);
            }
            refreshView();
        });
    })
}
//删除影视数据
const deleteMTV = (id)=>{
    //询问用户是否删除
ElMessageBox.confirm(
'确定永久性删除ID为 '+id+' 的数据吗?',
'警告',
{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal:false,
    closeOnPressEscape:false,	
    draggable:true,
    showClose:false,
    type: 'warning',
    center: true,
}).then(() => {
      //向后端发起删除请求
      IdentifyUser(id,'single');
}).catch(() => {
})
}
//管理员身份核验
const IdentifyUser = (i,type)=>{
 //要求超级管理员进行密码核验
 ElMessageBox.prompt('请输入您账户的密码', '身份核实', {
    confirmButtonText: '确定',
    inputType: 'password',
    showCancelButton:false,
    draggable:true,
    closeOnClickModal:false,
    closeOnPressEscape:false,
    center:true,
    inputPattern:/^[^\s]+$/,
    inputErrorMessage: '密码不为空',
    }).then(({ value }) => {
        if(type === 'single'){
            deleteMtvInfo({id:i,password:value}).then(res=>{
            if(res.status.code === 200){
            ElMessage({message: res.status.msg,type: 'success'});
            refreshView();
            if(mtvTable.value.length === 0){
                currentPage.value -= 1;
            }
            }else{
                ElMessage.error(res.status.msg);
            }
        })
        }else if(type === 'batch'){
            deleteMtvInfoBatch({id:i,password:value}).then(res=>{
            if(res.status.code === 200){
            ElMessage({message: res.status.msg,type: 'success'});
            handleOperateAll('all');
            showFloatPanel.value = false;
            refreshView();
            if(mtvTable.value.length === 0){
                currentPage.value -= 1;
            }
            }else{
                ElMessage.error(res.status.msg);
            }
            })
        }
      
    }).catch(() => {})
}

let previewBox = ref(false);
//文件超限提醒
const exceedTip = ()=>{
  ElMessage({
    message: '每次只能上传一个文件',
    type: 'warning',
  })
}
//打开预览图
const openPreviewBox = (val)=>{
    previewBox.value = val;
}
//获取选择的文件
const getImportFile = (file)=>{
    let type = file.raw.type;
    if(type.includes('image')){
        let id = posterList.value.length;
        posterList.value.push({id,name:file.raw.name,operate:['查看图片','删除图片'],file:file.raw,preview:null,match:null});
        posterList.value = unique(posterList.value,'name');
        checkMatchButton();
    }else{
        importFile.value = file.raw;
    }
}
//检查匹配海报按钮情况
const checkMatchButton = ()=>{
    if(posterList.value.length === importedList.value.length && importedList.value.length !== 0){
        showMatchButton.value=true;
    }
}
//匹配海报
const matchPoster = ()=>{
    //posterList,importedList
    //电影名和选择的图片名相匹配，相似度最高的即视为匹配成功
    //将原生文件对象的名字直接修改为匹配的海报图片名,然后获取到这个最终匹配文件对象数组
    posterList.value = matchAndReplace(posterList.value,importedList.value);
    //打开上传按钮
    showUploadButton.value = true;
}
//清空选择的文件
const removeImportFile = (type)=>{
    if(type == 'table'){
        importFile.value = null;
    }
    isShowProgressBar.value = false;
    checkMatchButton();
}

//查看当前的图片
const viewPoster = async (id)=>{
    //根据id找到对应的图片
    let item = posterList.value.filter(item => item.id === id);
    if(item[0].preview) return;
    //将文件对象转换成base64图片
    let url = await fileToDataURL(item[0].file);
    item[0].preview = url;
}
//删除当前的图片
const deletePoster = (id)=>{
    posterList.value = posterList.value.filter(item => item.id !== id);
    checkMatchButton();
}


//清空所有文件
const clearAllFiles = ()=>{
    importedList.value.length=0;
    posterList.value.length=0;
}
//数据发给后端
const submitImportFile = (type)=>{
    if(type === 'table'){
            let file = importFile.value;
        if(file){
            //判断文件类型
            let acceptFileType = ['text/csv','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-excel'];
            if(!acceptFileType.includes(file.type)) {
                ElMessage({
                    message: '当前文件格式不支持',
                    type: 'error',
                })
                return;
            }
            const formData = new FormData();
            formData.append('importFile',file);
            isShowProgressBar.value = true;
            importMtvInfo(formData).then(res=>{
                if(res.status.code === 200){
                    ElMessage({message: '导入成功',type: 'success',});
                    fileRef.value.clearFiles(); 
                    //获取插入的数据
                    getReturnData(res.data);
                    ElNotification({title: 'Success',message: '恭喜你完成第一步，请进入第二步',type: 'success',});
                    showChoosePoster.value = true;
                    showChooseFile.value = true;
                    //getMtvList();
                }else{
                    ElMessage({message:res.status.msg,type: 'error',});
                }
            });
        }else{
            ElMessage({
                message: '请选择要导入的文件',
                type: 'warning',
            });
        }
    }else{
        let fileList = posterList.value;
        if(fileList.length>0){
            //判断文件类型
            for(let i in fileList){
                let acceptFileType = ['image/webp'];
                if(!acceptFileType.includes(fileList[i].file.type)) {
                    deletePoster(fileList[i].id);
                    return;
                }
            }
            const formData = new FormData();
            let tempArr = [];
            for(let item of  posterList.value){
                tempArr.push({file:item.file,name:item.match});
            }
            tempArr.forEach(item=>{
                //修改文件对象的名字
                let newFile = renameFile(item.file,item.name);
                formData.append('file',newFile);
            });
            importMtvPosters(formData).then(res=>{
                if(res.status.code === 200){
                    ElMessage({message: '导入成功',type: 'success',});
                    showChoosePoster.value = false;
                    showChooseFile.value = false;
                    showUploadButton.value = false;
                }else{
                    ElMessage({message: res.status.msg,type: 'error',});
                }
                showResult.value = true;
                posterResult.value = res.data.info;
                successCount.value = res.data.successCount;
                errorCount.value = res.data.info.length;
            });
        }else{
            ElMessage({
                message: '请选择要导入的图片',
                type: 'warning',
              });
        }
    } 
}
//获取返回的数据
const getReturnData=(data)=>{
    importedList.value = data;
}
</script>
  
<style lang="scss" scoped>
@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
:deep(.el-image__wrapper){
    @include flex-center;
}
:deep(.el-table){
    .cell{
        text-wrap:nowrap;
    }
    .el-table__cell{
        height:49px;
    }
}
.result-info-container{
    display:flex;
}
.poster-wrapper{
    @include flex-center;
}
.import-file{
        width:max-content;
        display: flex;
        align-items:baseline;
        margin-top:5px;
        :deep(.el-upload-list){
            width:200px;
        }
    }
.import-container{
    display:flex;
    justify-content: center;
    .left-file-zone,.right-file-zone{
        flex:0.5;
        display:flex;
        flex-direction:column;
        justify-content:flex-start;
        .guide{
            display:inline-block;
            height:40px;
        }
       }
}
.poster-preview{
    display:block;
    width:270px;
    height:400px;
    object-fit:contain;
    margin:0 auto;
    box-shadow: 0 0 10px #000000ad;
}
.user-mute{
    @include flex-center;
    flex-direction: column;
    width:100%;
    label{
        width:100px;
    }
    .day-wrapper{
        display:flex;
        margin-bottom: 10px;
    }
}
.mtv-info-container{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
}
.mtv-table-wrapper{
    display:flex;
    flex-direction: column;
    justify-content: flex-start;
    height: 100%;
}
label{
    display: inline-block;
    width: 50px;
    font-size: 14px;
    line-height: 30px;
    color: #606266;
}
.top-query{
    display: flex;
    width:100%;
    height:50px;
    margin-top:20px;
    justify-content: space-around;
    .class-filter{
        display: flex;
        :deep(.el-radio-group){
            display: block !important;
        }
    }
    
}
:deep(.el-select__wrapper){
    min-width:180px;
}  
.user-avatar{
    display: inline-block;
    width:80px;
    height: 80px;
    border-radius: 50%;
}
.user-table{
    width:99% !important;
    margin: 0 auto;
    height: 65vh;
}
.pagination{
    display: flex;
    justify-content: center;
    align-items: center;
    margin:5px;
}
.preview-img{
    width:270px;
    max-height:400px;
    min-height:380px;
    img{
        width:100%;
        height:100%;
        object-fit: cover;
    }
}
</style>
  